package com.sys.dispatch;

import java.util.Date;
import java.util.List;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.sys.db.dao.DefFlowDao;
import com.sys.db.util.ExtendDate;
import com.sys.db.util.GetBeanUtil;
import com.sys.db.util.ThreadArray;
import com.sys.pojo.DefFlow;

public class FlowTimerTask extends TimerTask{
	protected static Logger log = Logger.getLogger(FlowThread.class);
	@Override
	public void run() {
//		String[] context={"applicationContext-dao.xml","applicationContext-database.xml"};
//		ApplicationContext ctx = new ClassPathXmlApplicationContext(context);
//		DefFlowDao defDao = (DefFlowDao) ctx.getBean("defFlowDaoImpl");
		DefFlowDao defDao=(DefFlowDao) GetBeanUtil.getDao("defFlowDaoImpl");
		String time=ExtendDate.getSysN0SecDate();
		String timeH=time.split(" ")[1];
		System.out.println("系统时间："+timeH);
		try {
			List<DefFlow> list=defDao.findByTime(timeH);
//			List<DefFlow> list=defDao.findAll();
			int a=0;
			if(list!=null && list.size()>0){
				for(int i=0;i<list.size();i++){
					DefFlow def=list.get(i);
					if(validateFlow(def)){
						FlowThread ft=new FlowThread(def);
						ThreadArray.addThread(def.getFlowId(), ft);
						ft.start();
					}
				}
			}
//			log.info("当前时间要跑的作业流有"+a+"个");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 验证作业流是否需要运行
	 * @param defFlow
	 * @return
	 */
	public boolean validateFlow(DefFlow defFlow){
		String sysTime=ExtendDate.getStringDonversionDate(new Date());
		int dayOfMonth=new Integer(sysTime.split("-")[2]);
		int monthOfYear=new Integer(sysTime.split("-")[1]);
		String type=defFlow.getFreType();//运行类型
		int delay=defFlow.getDataDelay();
		if("D".equals(type)){
			return true;
		}else if(dayOfMonth==delay){
			if("M".equals(type)){
				return true;
			}else if("S".equals(type)){
				if(monthOfYear==1||monthOfYear==4||monthOfYear==7||monthOfYear==10){
					return true;
				}
			}else if("Y".equals(type)){
				if(monthOfYear==1){
					return true;
				}
			}
		}
		return false;
	}
}
